#!/usr/bin/env python

import os
import subprocess
import socket
import sys
import time
from struct import *

import paho.mqtt.client as mqtt

sent_mid = -1

def on_connect(mqttc, obj, flags, rc):
    global sent_mid
    if rc != 0:
        exit(rc)
    else:
        if sent_mid == -1:
            res = mqttc.publish("pub/qos1/test", "message", 1)
            sent_mid = res[1]

def on_disconnect(mqttc, obj, rc):
    if rc == 1:
        mqttc.reconnect()
    else:
        run = 0

def on_publish(mqttc, obj, mid):
    global sent_mid
    if mid == sent_mid:
        mqttc.disconnect()
    else:
        exit(1)

mqttc = mqtt.Client("publish-qos1-test", clean_session=False)
mqttc.message_retry_set(3)
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish

mqttc.connect("localhost", 1888)
rc = 0
while True:
    rc = mqttc.loop()
